<?php
namespace app\facility\controller;

use think\Controller;
use app\facility\model\ESP8266Sniffing;
use app\facility\model\ESP8266Mobile;
use think\Db;

class Esp extends Controller
{
    public function add_mac($data = "", $id = "", $temp = 0, $currentSecond = 0, $uploadCount = 0)
    {
        if ($id == "") {
            return "no";
        }
        write_log(" message data:" . $data, 3);
        $deviceId = $id;
        $check_array = explode(";", $data);
        $data = "";
        foreach ($check_array as $check_item) {
            if ($check_item != "") {
                $c_temp = explode("|", $check_item);
                if (sizeof($c_temp) == 2 && strlen($c_temp[0]) == 17) {
                    $data .= $check_item . ";";
                    $data++;
                }
            }
        }
        write_log(" thire data:" . $data, 3);
        $mobileData = explode(";", $data);
        $mCount = sizeof($mobileData) - 1;
        $pid = -1;
        write_log(" ESP8266Sniffing data:start", 3);
        //保存主表
        $sModel = new ESP8266Sniffing;
        $sModel->device_id = $deviceId;
        $sModel->mobile_count = $mCount;
        $sModel->temp = $temp;
        $sModel->add_time = date('Y-m-d H:i:s');
        $sModel->save();
        $pid = $sModel->id;
        write_log(" ESP8266Sniffing data:" . $pid, 3);
        if (sizeof($mobileData) > 1) {
            $curtime = time();
            $count1 = 0;
            $count2 = 0;
            foreach ($mobileData as $item) {
                if ($item != "") {
                    $count1++;
                    $count2 = $this->addSubData($pid, $item, $currentSecond, $curtime, $count2);
                }
            }
            $insert_data = ['device_id' => $deviceId, 'content' => ''
                , 'temp' => $temp, 'upload_count' => $uploadCount
                , 'add_time' => date('Y-m-d H:i:s'), 'mac_count' => $count1
                , 'valid_mac_count' => $count2];
            $pid = Db::name('http_sniffer')->insertGetId($insert_data);
        }
    }

    private function addSubData($pid, $data, $currentSecond, $curtime, $count2)
    {
        $arraylist = explode("|", $data);
        if (sizeof($arraylist) == 2) {
            $t1 = $currentSecond - $arraylist[1];
            $t2 = $curtime - $t1;
            $moible = new ESP8266Mobile;
            $moible->pid = $pid;
            $moible->mac = $arraylist[0];
            $moible->add_time = date("Y-m-d H:i:s", $t2);
            $moible->save();
            $count2++;
        }
        return $count2;
    }
}